package com.service.admin.impl;

import com.dao.WalletDao;
import com.entity.Notice;
import com.entity.WalletRecord;
import com.service.admin.AdminWalletService;
import com.service.user.NoticeService;
import com.utils.FileUploadUtil;
import com.utils.SqlSessionGetter;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**  */
@Service
public class AdminWalletServiceImpl implements AdminWalletService {
  @Autowired NoticeService noticeService;

  @Override
  public Map<String, Integer> getWithdrawRecordCount() {
    SqlSession session = SqlSessionGetter.getSqlSession();
    WalletDao dao = session.getMapper(WalletDao.class);
    Map<String, Integer> ret = dao.selectWithdrawRecordCount();
    session.close();
    return ret;
  }

  @Override
  public List<Map<String, Object>> getWithdrawalRecord(
      String userId, int deal, Integer pageSize, Integer pageIndex) {
    List<Map<String, Object>> record = null;
    SqlSession session = SqlSessionGetter.getSqlSession();
    WalletDao dao = session.getMapper(WalletDao.class);
    try {
      Integer start = (pageSize == null ? null : pageSize * pageIndex);
      record = dao.selectWithdrawRecords(userId, deal, start, pageSize);
    } catch (Exception e) {
      System.err.println("获取提现记录sql错误");
    }
    session.close();
    return record;
  }

  @Override
  public int dealWithDraw(int id, String adminName, MultipartFile file) {
    // 保存新的图片
    String imageURL =
        FileUploadUtil.uploadFile(
            file,
            UUID.randomUUID().toString().replace("-", ""),
            FileUploadUtil.WITHDRAW_RESULT_SUBDIR,
            FileUploadUtil.IMAGE_SUFFIX);
    if (imageURL == null) {
      // 文件格式错误
      return 0;
    }

    SqlSession session = SqlSessionGetter.getSqlSession();
    WalletDao dao = session.getMapper(WalletDao.class);
    // 记录处理结果
    dao.updateWithDrawResult(id, imageURL, adminName);
    session.commit();
    Map<String, Object> record = dao.selectWithdrawRecord(id);
    String userId = (String) record.get("userId");
    float count = (float) record.get("count");
    Date time = (Date) record.get("time");
    // 更新用户账户金额
    dao.updateCoinCount(userId, 0, -count);
    session.commit();
    // 添加流水记录
    dao.insertWalletRecord(userId, count, WalletRecord.WITHDRAWAL);
    session.commit();
    session.close();

    // 添加通知
    noticeService.addNotice(userId, Notice.WITHDRAW_SUCCESS, null, 0, time, count, imageURL);
    return 1;
  }
}
